package com.mofang.ticketing.common.file.config;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * 阿里云OSS参数
 *
 * @author 王智宇
 * @module star-sand
 * @date 2021/7/15 14:06
 * @copyright 2021 mofang. All rights reserved
 */
@Data
@Slf4j
@Configuration
public class AliyunOSSConfig {

    /**
     * 阿里云API的密钥Access Key ID
     */
    @Value("${aliyun.access-key-id}")
    private String access_key_id;

    /**
     * 阿里云API的密钥Access Key Secret
     */
    @Value("${aliyun.access-key-secret}")
    private String access_key_secret;

    /**
     * 阿里云API的内或外网域名
     */
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    /**
     * 阿里云API的存储空间（Bucket）名称
     */
    @Value("${aliyun.oss.bucket-name}")
    private String bucket_name;

    /**
     * 阿里云API的文件夹名称
     */
    @Value("${aliyun.oss.folder}")
    private String folder;

    /**
     * 获取阿里云OSS客户端对象
     *
     * @return ossClient
     */
    public OSSClient createOSSClient() {
        return new OSSClient(endpoint, access_key_id, access_key_secret);
    }
    public OSSClient createOSSClient(String endpoint) {
        return new OSSClient(endpoint, access_key_id, access_key_secret);
    }
    public OSSClient createOSSClient(String endpoint,String accessKeyId,String accessKeySecret) {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 创建存储空间
     *
     * @param ossClient  OSS连接
     * @param bucketName 存储空间
     * @return
     */
    public String createBucketName(OSSClient ossClient, String bucketName) {
        // 存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            log.info("创建存储空间{}成功",bucketName);
            return bucket.getName();
        }
        return bucketName;
    }

    /**
     * 删除存储空间buckName
     *
     * @param ossClient oss对象
     * @param bucketName 存储空间
     */
    public void deleteBucket(OSSClient ossClient, String bucketName) {
        ossClient.deleteBucket(bucketName);
        log.info("删除存储空间{}成功",bucketName);
    }
}
